package com.pethospital.servlet;

import com.pethospital.entity.PageResult;
import com.pethospital.entity.User;
import com.pethospital.service.UserService;
import com.pethospital.service.impl.UserServiceImpl;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 * User Controller Servlet
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class UserServlet extends HttpServlet {
    
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 从URL路径获取操作类型
        String pathInfo = request.getPathInfo();
        String action = pathInfo != null ? pathInfo.substring(1) : "";

        // 如果路径中没有操作，尝试从参数中获取
        if (action.isEmpty()) {
            action = request.getParameter("action");
            if (action == null) {
                action = "";
            }
        }
        
        try {
            switch (action) {
                case "login":
                    handleLogin(request, response);
                    break;
                case "register":
                    handleRegister(request, response);
                    break;
                case "logout":
                    handleLogout(request, response);
                    break;
                case "list":
                    handleList(request, response);
                    break;
                case "add":
                    handleAdd(request, response);
                    break;
                case "edit":
                    handleEdit(request, response);
                    break;
                case "update":
                    handleUpdate(request, response);
                    break;
                case "delete":
                    handleDelete(request, response);
                    break;
                case "batchDelete":
                    handleBatchDelete(request, response);
                    break;
                case "updateStatus":
                    handleUpdateStatus(request, response);
                    break;
                case "updatePassword":
                    handleUpdatePassword(request, response);
                    break;
                case "resetPassword":
                    handleResetPassword(request, response);
                    break;
                case "checkUsername":
                    handleCheckUsername(request, response);
                    break;
                case "profile":
                    handleProfile(request, response);
                    break;
                case "updateProfile":
                    handleUpdateProfile(request, response);
                    break;
                case "changePassword":
                    handleChangePassword(request, response);
                    break;
                case "import":
                    handleImport(request, response);
                    break;
                case "downloadTemplate":
                    handleDownloadTemplate(request, response);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的操作");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
        }
    }
    
    /**
     * 处理用户登录
     */
    private void handleLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        if (username == null || username.trim().isEmpty() || 
            password == null || password.trim().isEmpty()) {
            request.setAttribute("error", "用户名和密码不能为空");
            request.getRequestDispatcher("/pages/common/login.jsp").forward(request, response);
            return;
        }
        
        User user = userService.login(username.trim(), password);
        if (user != null) {
            // 登录成功，将用户信息存入session
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", user);
            
            // 根据用户类型跳转到不同页面
            if ("admin".equals(user.getUserType())) {
                response.sendRedirect(request.getContextPath() + "/pages/admin/dashboard.jsp");
            } else {
                response.sendRedirect(request.getContextPath() + "/pages/user/dashboard.jsp");
            }
        } else {
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("/pages/common/login.jsp").forward(request, response);
        }
    }
    
    /**
     * 处理用户注册
     */
    private void handleRegister(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String realName = request.getParameter("realName");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");
        
        // 验证密码确认
        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的密码不一致");
            request.getRequestDispatcher("/pages/common/register.jsp").forward(request, response);
            return;
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRealName(realName);
        user.setPhone(phone);
        user.setEmail(email);
        user.setAddress(address);
        user.setUserType("user"); // 注册的用户默认为普通用户
        
        // 验证用户数据
        String validationResult = userService.validateUser(user, false);
        if (validationResult != null) {
            request.setAttribute("error", validationResult);
            request.getRequestDispatcher("/pages/common/register.jsp").forward(request, response);
            return;
        }
        
        // 检查用户名是否已存在
        if (userService.isUsernameExists(username)) {
            request.setAttribute("error", "用户名已存在");
            request.getRequestDispatcher("/pages/common/register.jsp").forward(request, response);
            return;
        }
        
        // 检查邮箱是否已存在
        if (email != null && !email.trim().isEmpty() && userService.isEmailExists(email)) {
            request.setAttribute("error", "邮箱已被使用");
            request.getRequestDispatcher("/pages/common/register.jsp").forward(request, response);
            return;
        }
        
        // 注册用户
        if (userService.register(user)) {
            request.setAttribute("success", "注册成功，请登录");
            request.getRequestDispatcher("/pages/common/login.jsp").forward(request, response);
        } else {
            request.setAttribute("error", "注册失败，请重试");
            request.getRequestDispatcher("/pages/common/register.jsp").forward(request, response);
        }
    }
    
    /**
     * 处理用户登出
     */
    private void handleLogout(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        
        response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
    }
    
    /**
     * 处理用户列表查询
     */
    private void handleList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 获取查询参数
        String username = request.getParameter("username");
        String realName = request.getParameter("realName");
        String userType = request.getParameter("userType");
        String status = request.getParameter("status");

        // 获取排序参数
        String sortField = request.getParameter("sortField");
        String sortOrder = request.getParameter("sortOrder");

        // 设置默认排序
        if (sortField == null || sortField.trim().isEmpty()) {
            sortField = "createTime";
        }
        if (sortOrder == null || sortOrder.trim().isEmpty()) {
            sortOrder = "desc";
        }

        // 获取分页参数
        int currentPage = 1;
        int pageSize = 10;
        
        try {
            String pageStr = request.getParameter("page");
            if (pageStr != null && !pageStr.trim().isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }
            
            String sizeStr = request.getParameter("size");
            if (sizeStr != null && !sizeStr.trim().isEmpty()) {
                pageSize = Integer.parseInt(sizeStr);
            }
        } catch (NumberFormatException e) {
            // 使用默认值
        }
        
        // 查询用户列表
        PageResult<User> pageResult = userService.searchUsers(username, realName, userType, status,
                                                            sortField, sortOrder, currentPage, pageSize);

        // 设置请求属性
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("username", username);
        request.setAttribute("realName", realName);
        request.setAttribute("userType", userType);
        request.setAttribute("status", status);
        request.setAttribute("sortField", sortField);
        request.setAttribute("sortOrder", sortOrder);
        request.setAttribute("pageSize", pageSize);
        
        // 转发到用户列表页面
        request.getRequestDispatcher("/pages/admin/user-list.jsp").forward(request, response);
    }

    /**
     * 处理添加用户
     */
    private void handleAdd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // GET请求：显示添加页面
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            request.getRequestDispatcher("/pages/admin/user-add.jsp").forward(request, response);
            return;
        }

        // POST请求：处理添加操作
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String realName = request.getParameter("realName");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");
        String userType = request.getParameter("userType");
        String status = request.getParameter("status");

        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRealName(realName);
        user.setPhone(phone);
        user.setEmail(email);
        user.setAddress(address);
        user.setUserType(userType);
        user.setStatus(status != null ? status : "active");

        // 注册用户
        if (userService.register(user)) {
            try {
                String successMsg = URLEncoder.encode("添加成功", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/user/list?success=" + successMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/user/list");
            }
        } else {
            request.setAttribute("error", "添加失败");
            request.setAttribute("user", user);
            request.getRequestDispatcher("/pages/admin/user-add.jsp").forward(request, response);
        }
    }

    /**
     * 处理编辑用户页面
     */
    private void handleEdit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userIdStr = request.getParameter("id");
        if (userIdStr == null || userIdStr.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID不能为空");
            return;
        }

        try {
            Integer userId = Integer.parseInt(userIdStr);
            User user = userService.getUserById(userId);

            if (user != null) {
                request.setAttribute("user", user);
                request.getRequestDispatcher("/pages/admin/user-edit.jsp").forward(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "用户不存在");
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID格式错误");
        }
    }

    /**
     * 处理更新用户
     */
    private void handleUpdate(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userIdStr = request.getParameter("userId");
        String realName = request.getParameter("realName");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");
        String userType = request.getParameter("userType");
        String status = request.getParameter("status");

        try {
            Integer userId = Integer.parseInt(userIdStr);

            // 获取原用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "用户不存在");
                return;
            }

            // 更新用户信息
            user.setRealName(realName);
            user.setPhone(phone);
            user.setEmail(email);
            user.setAddress(address);
            user.setUserType(userType);
            user.setStatus(status);

            if (userService.updateUser(user)) {
                try {
                    String successMsg = URLEncoder.encode("更新成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/list?success=" + successMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/user/list");
                }
            } else {
                request.setAttribute("error", "更新失败");
                request.setAttribute("user", user);
                request.getRequestDispatcher("/pages/admin/user-edit.jsp").forward(request, response);
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID格式错误");
        }
    }

    /**
     * 处理删除用户
     */
    private void handleDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userIdStr = request.getParameter("id");
        if (userIdStr == null || userIdStr.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID不能为空");
            return;
        }

        try {
            Integer userId = Integer.parseInt(userIdStr);

            if (userService.deleteUser(userId)) {
                try {
                    String successMsg = URLEncoder.encode("删除成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/list?success=" + successMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/user/list");
                }
            } else {
                try {
                    String errorMsg = URLEncoder.encode("删除失败", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/list?error=" + errorMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/user/list");
                }
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID格式错误");
        }
    }

    /**
     * 处理批量删除用户
     */
    private void handleBatchDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String[] userIdStrs = request.getParameterValues("userIds");
        if (userIdStrs == null || userIdStrs.length == 0) {
            try {
                String errorMsg = URLEncoder.encode("请选择要删除的用户", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/user/list?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/user/list");
            }
            return;
        }

        try {
            Integer[] userIds = new Integer[userIdStrs.length];
            for (int i = 0; i < userIdStrs.length; i++) {
                userIds[i] = Integer.parseInt(userIdStrs[i]);
            }

            if (userService.batchDeleteUsers(userIds)) {
                try {
                    String successMsg = URLEncoder.encode("批量删除成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/list?success=" + successMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/user/list");
                }
            } else {
                try {
                    String errorMsg = URLEncoder.encode("批量删除失败", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/list?error=" + errorMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/user/list");
                }
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID格式错误");
        }
    }

    /**
     * 处理更新用户状态
     */
    private void handleUpdateStatus(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置响应类型
        response.setContentType("text/plain;charset=UTF-8");

        String userIdStr = request.getParameter("id");
        String status = request.getParameter("status");

        if (userIdStr == null || userIdStr.trim().isEmpty() ||
            status == null || status.trim().isEmpty()) {
            response.getWriter().write("error");
            return;
        }

        try {
            Integer userId = Integer.parseInt(userIdStr);

            if (userService.updateUserStatus(userId, status)) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("error");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("error");
        }
    }

    /**
     * 处理更新密码
     */
    private void handleUpdatePassword(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userIdStr = request.getParameter("userId");
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        // 验证参数
        if (userIdStr == null || oldPassword == null || newPassword == null || confirmPassword == null) {
            request.setAttribute("error", "参数不能为空");
            request.getRequestDispatcher("/pages/common/change-password.jsp").forward(request, response);
            return;
        }

        // 验证新密码确认
        if (!newPassword.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的新密码不一致");
            request.getRequestDispatcher("/pages/common/change-password.jsp").forward(request, response);
            return;
        }

        try {
            Integer userId = Integer.parseInt(userIdStr);

            if (userService.updatePassword(userId, oldPassword, newPassword)) {
                request.setAttribute("success", "密码修改成功");
                request.getRequestDispatcher("/pages/common/change-password.jsp").forward(request, response);
            } else {
                request.setAttribute("error", "密码修改失败，请检查原密码是否正确");
                request.getRequestDispatcher("/pages/common/change-password.jsp").forward(request, response);
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID格式错误");
        }
    }

    /**
     * 处理重置密码（管理员功能）
     */
    private void handleResetPassword(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userIdStr = request.getParameter("id");
        String newPassword = request.getParameter("newPassword");

        if (userIdStr == null || userIdStr.trim().isEmpty() ||
            newPassword == null || newPassword.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "参数不能为空");
            return;
        }

        try {
            Integer userId = Integer.parseInt(userIdStr);

            if (userService.resetPassword(userId, newPassword)) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("error");
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID格式错误");
        }
    }

    /**
     * 处理检查用户名是否存在
     */
    private void handleCheckUsername(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        if (username == null || username.trim().isEmpty()) {
            response.getWriter().write("false");
            return;
        }

        boolean exists = userService.isUsernameExists(username.trim());
        response.getWriter().write(exists ? "true" : "false");
    }

    /**
     * 处理用户个人资料
     */
    private void handleProfile(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        // 获取最新的用户信息
        User user = userService.getUserById(currentUser.getUserId());
        if (user != null) {
            request.setAttribute("user", user);
            request.getRequestDispatcher("/pages/common/profile.jsp").forward(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "用户不存在");
        }
    }

    /**
     * 处理更新个人资料
     */
    private void handleUpdateProfile(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String realName = request.getParameter("realName");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");

        // 验证必填字段
        if (realName == null || realName.trim().isEmpty()) {
            try {
                String errorMsg = URLEncoder.encode("真实姓名不能为空", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/user/profile?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/user/profile");
            }
            return;
        }

        // 更新用户信息
        User user = userService.getUserById(currentUser.getUserId());
        if (user != null) {
            user.setRealName(realName);
            user.setPhone(phone);
            user.setEmail(email);
            user.setAddress(address);

            if (userService.updateUser(user)) {
                // 更新session中的用户信息
                session.setAttribute("currentUser", user);

                try {
                    String successMsg = URLEncoder.encode("个人资料更新成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/profile?success=" + successMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/user/profile");
                }
            } else {
                try {
                    String errorMsg = URLEncoder.encode("更新失败，请重试", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/profile?error=" + errorMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/user/profile");
                }
            }
        } else {
            try {
                String errorMsg = URLEncoder.encode("用户不存在", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/user/profile?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/user/profile");
            }
        }
    }

    /**
     * 处理修改密码
     */
    private void handleChangePassword(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String currentPassword = request.getParameter("currentPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        // 验证必填字段
        if (currentPassword == null || currentPassword.trim().isEmpty() ||
            newPassword == null || newPassword.trim().isEmpty() ||
            confirmPassword == null || confirmPassword.trim().isEmpty()) {

            try {
                String errorMsg = URLEncoder.encode("请填写所有字段", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp");
            }
            return;
        }

        // 验证新密码长度
        if (newPassword.length() < 6) {
            try {
                String errorMsg = URLEncoder.encode("新密码长度至少6位", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp");
            }
            return;
        }

        // 验证两次输入的新密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            try {
                String errorMsg = URLEncoder.encode("两次输入的新密码不一致", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp");
            }
            return;
        }

        // 验证当前密码是否正确
        User user = userService.login(currentUser.getUsername(), currentPassword);
        if (user == null) {
            try {
                String errorMsg = URLEncoder.encode("当前密码错误", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp");
            }
            return;
        }

        // 检查新密码是否与当前密码相同
        if (currentPassword.equals(newPassword)) {
            try {
                String errorMsg = URLEncoder.encode("新密码不能与当前密码相同", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp");
            }
            return;
        }

        // 更新密码
        if (userService.updatePassword(currentUser.getUserId(), newPassword)) {
            try {
                String successMsg = URLEncoder.encode("密码修改成功", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp?success=" + successMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp");
            }
        } else {
            try {
                String errorMsg = URLEncoder.encode("密码修改失败，请重试", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/pages/common/change-password.jsp");
            }
        }
    }

    /**
     * 处理用户导入
     */
    private void handleImport(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 检查管理员权限
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("{\"success\":false,\"message\":\"权限不足\"}");
            return;
        }

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            // 检查是否为multipart请求
            if (!ServletFileUpload.isMultipartContent(request)) {
                out.write("{\"success\":false,\"message\":\"请选择文件\"}");
                return;
            }

            // 创建文件上传处理器
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(10 * 1024 * 1024); // 10MB
            upload.setSizeMax(10 * 1024 * 1024);

            List<FileItem> items = upload.parseRequest(request);
            FileItem fileItem = null;
            boolean skipDuplicates = false;

            // 解析请求参数
            for (FileItem item : items) {
                if (item.isFormField()) {
                    if ("skipDuplicates".equals(item.getFieldName())) {
                        skipDuplicates = "true".equals(item.getString());
                    }
                } else if ("importFile".equals(item.getFieldName())) {
                    fileItem = item;
                }
            }

            if (fileItem == null || fileItem.getSize() == 0) {
                out.write("{\"success\":false,\"message\":\"请选择要导入的文件\"}");
                return;
            }

            // 验证文件类型
            String fileName = fileItem.getName().toLowerCase();
            if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
                out.write("{\"success\":false,\"message\":\"请选择Excel文件（.xlsx或.xls格式）\"}");
                return;
            }

            // 解析Excel文件
            List<User> users = parseExcelFile(fileItem.getInputStream());
            System.out.println("解析到的用户数量: " + users.size());

            if (users.isEmpty()) {
                out.write("{\"success\":false,\"message\":\"Excel文件中没有有效的用户数据，请检查文件格式是否正确\"}");
                return;
            }

            // 导入用户数据
            Map<String, Object> result = importUsers(users, skipDuplicates);

            System.out.println("导入结果 - 成功: " + result.get("success") +
                             ", 跳过: " + result.get("skip") +
                             ", 失败: " + result.get("error"));

            Integer successCount = (Integer) result.get("success");
            Integer skipCount = (Integer) result.get("skip");
            Integer errorCount = (Integer) result.get("error");

            if (successCount == 0 && skipCount == 0) {
                String errorDetails = (String) result.get("errorDetails");
                out.write("{\"success\":false,\"message\":\"导入失败，共" + errorCount + "个用户导入失败。" +
                         (errorDetails != null && !errorDetails.isEmpty() ? "错误详情：" + errorDetails : "请检查数据格式和是否有重复数据") + "\"}");
            } else {
                out.write("{\"success\":true,\"successCount\":" + successCount +
                         ",\"skipCount\":" + skipCount +
                         ",\"errorCount\":" + errorCount + "}");
            }

        } catch (Exception e) {
            e.printStackTrace();
            out.write("{\"success\":false,\"message\":\"导入失败：" + e.getMessage() + "\"}");
        } finally {
            out.close();
        }
    }

    /**
     * 处理下载导入模板
     */
    private void handleDownloadTemplate(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 检查管理员权限
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "权限不足");
            return;
        }

        try {
            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("用户导入模板");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"用户名*", "真实姓名*", "用户类型*", "手机号", "邮箱", "地址", "状态*"};

            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 添加示例数据（请删除此行，填入真实数据）
            Row exampleRow = sheet.createRow(1);
            exampleRow.createCell(0).setCellValue("示例用户名1");
            exampleRow.createCell(1).setCellValue("示例姓名1");
            exampleRow.createCell(2).setCellValue("user");
            exampleRow.createCell(3).setCellValue("13800138000");
            exampleRow.createCell(4).setCellValue("example1@yourcompany.com");
            exampleRow.createCell(5).setCellValue("示例地址1");
            exampleRow.createCell(6).setCellValue("active");

            // 添加第二个示例（请删除此行，填入真实数据）
            Row example2Row = sheet.createRow(2);
            example2Row.createCell(0).setCellValue("示例用户名2");
            example2Row.createCell(1).setCellValue("示例姓名2");
            example2Row.createCell(2).setCellValue("user");
            example2Row.createCell(3).setCellValue("13900139000");
            example2Row.createCell(4).setCellValue("example2@yourcompany.com");
            example2Row.createCell(5).setCellValue("示例地址2");
            example2Row.createCell(6).setCellValue("active");

            // 添加说明行
            Row noteRow = sheet.createRow(4);
            noteRow.createCell(0).setCellValue("说明：");

            Row note1Row = sheet.createRow(5);
            note1Row.createCell(0).setCellValue("1. 带*号的字段为必填项");

            Row note2Row = sheet.createRow(6);
            note2Row.createCell(0).setCellValue("2. 用户类型：admin（管理员）或 user（普通用户）");

            Row note3Row = sheet.createRow(7);
            note3Row.createCell(0).setCellValue("3. 状态：active（正常）或 inactive（禁用）");

            Row note4Row = sheet.createRow(8);
            note4Row.createCell(0).setCellValue("4. 默认密码为：123456，用户首次登录后请修改");

            Row note5Row = sheet.createRow(9);
            note5Row.createCell(0).setCellValue("5. 请删除示例数据行，填入真实用户数据");

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 设置响应头
            String fileName = URLEncoder.encode("用户导入模板_" + new SimpleDateFormat("yyyyMMdd").format(new java.util.Date()) + ".xlsx", "UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 写入响应
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "生成模板失败");
        }
    }

    /**
     * 解析Excel文件
     */
    private List<User> parseExcelFile(InputStream inputStream) throws Exception {
        List<User> users = new ArrayList<>();

        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);

        System.out.println("Excel文件总行数: " + (sheet.getLastRowNum() + 1));

        // 跳过标题行，从第二行开始读取数据
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                System.out.println("第" + (i+1) + "行为空，跳过");
                continue;
            }

            // 检查是否为空行
            boolean isEmptyRow = true;
            for (int j = 0; j < 7; j++) {
                Cell cell = row.getCell(j);
                if (cell != null && cell.getCellType() != CellType.BLANK) {
                    String value = getCellValueAsString(cell);
                    if (value != null && !value.trim().isEmpty()) {
                        isEmptyRow = false;
                        break;
                    }
                }
            }

            if (isEmptyRow) {
                System.out.println("第" + (i+1) + "行为空行，跳过");
                continue;
            }

            try {
                System.out.println("正在解析第" + (i+1) + "行数据");
                User user = new User();

                // 用户名（必填）
                String username = getCellValueAsString(row.getCell(0));
                System.out.println("用户名: " + username);
                if (username == null || username.trim().isEmpty()) {
                    System.out.println("用户名为空，跳过第" + (i+1) + "行");
                    continue; // 跳过用户名为空的行
                }
                user.setUsername(username.trim());

                // 真实姓名（必填）
                String realName = getCellValueAsString(row.getCell(1));
                System.out.println("真实姓名: " + realName);
                if (realName == null || realName.trim().isEmpty()) {
                    System.out.println("真实姓名为空，跳过第" + (i+1) + "行");
                    continue; // 跳过真实姓名为空的行
                }
                user.setRealName(realName.trim());

                // 用户类型（必填）
                String userType = getCellValueAsString(row.getCell(2));
                if (userType == null || userType.trim().isEmpty()) {
                    userType = "user"; // 默认为普通用户
                }
                userType = userType.trim().toLowerCase();
                if (!"admin".equals(userType) && !"user".equals(userType)) {
                    userType = "user"; // 无效值默认为普通用户
                }
                user.setUserType(userType);

                // 手机号（可选）
                String phone = getCellValueAsString(row.getCell(3));
                if (phone != null && !phone.trim().isEmpty()) {
                    // 清理手机号格式，移除可能的空格和特殊字符
                    phone = phone.trim().replaceAll("[^0-9]", "");
                    if (phone.length() == 11 && phone.startsWith("1")) {
                        user.setPhone(phone);
                        System.out.println("手机号: " + phone);
                    } else {
                        System.out.println("手机号格式不正确，跳过: " + phone);
                    }
                }

                // 邮箱（可选）
                String email = getCellValueAsString(row.getCell(4));
                if (email != null && !email.trim().isEmpty()) {
                    user.setEmail(email.trim());
                }

                // 地址（可选）
                String address = getCellValueAsString(row.getCell(5));
                if (address != null && !address.trim().isEmpty()) {
                    user.setAddress(address.trim());
                }

                // 状态（必填）
                String status = getCellValueAsString(row.getCell(6));
                if (status == null || status.trim().isEmpty()) {
                    status = "active"; // 默认为正常状态
                }
                status = status.trim().toLowerCase();
                if (!"active".equals(status) && !"inactive".equals(status)) {
                    status = "active"; // 无效值默认为正常状态
                }
                user.setStatus(status);

                // 设置默认密码
                user.setPassword("123456");

                System.out.println("成功解析用户: " + user.getUsername() + ", 真实姓名: " + user.getRealName() +
                                 ", 类型: " + user.getUserType() + ", 状态: " + user.getStatus());

                users.add(user);

            } catch (Exception e) {
                System.out.println("解析第" + (i+1) + "行时发生异常: " + e.getMessage());
                e.printStackTrace();
                // 跳过解析失败的行
                continue;
            }
        }

        workbook.close();
        return users;
    }

    /**
     * 获取单元格值作为字符串
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) return null;

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
                } else {
                    // 处理数字，避免科学计数法
                    double numericValue = cell.getNumericCellValue();
                    if (numericValue == (long) numericValue) {
                        return String.valueOf((long) numericValue);
                    } else {
                        return String.valueOf(numericValue);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }

    /**
     * 导入用户数据
     */
    private Map<String, Object> importUsers(List<User> users, boolean skipDuplicates) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int skipCount = 0;
        int errorCount = 0;
        StringBuilder errorDetails = new StringBuilder();

        System.out.println("开始导入用户，总数: " + users.size() + ", 跳过重复: " + skipDuplicates);

        for (User user : users) {
            try {
                System.out.println("正在处理用户: " + user.getUsername());

                // 验证用户数据
                String validationResult = userService.validateUser(user, false);
                if (validationResult != null) {
                    System.out.println("用户验证失败: " + user.getUsername() + ", 原因: " + validationResult);
                    errorDetails.append("用户[").append(user.getUsername()).append("]: ").append(validationResult).append("; ");
                    errorCount++;
                    continue;
                }

                // 检查用户名是否已存在
                if (userService.isUsernameExists(user.getUsername())) {
                    System.out.println("用户名已存在: " + user.getUsername());
                    if (skipDuplicates) {
                        skipCount++;
                        continue;
                    } else {
                        errorDetails.append("用户[").append(user.getUsername()).append("]: 用户名已存在; ");
                        errorCount++;
                        continue;
                    }
                }

                // 检查邮箱是否已存在
                if (user.getEmail() != null && !user.getEmail().trim().isEmpty() &&
                    userService.isEmailExists(user.getEmail())) {
                    System.out.println("邮箱已存在: " + user.getEmail());
                    if (skipDuplicates) {
                        skipCount++;
                        continue;
                    } else {
                        errorDetails.append("用户[").append(user.getUsername()).append("]: 邮箱已存在; ");
                        errorCount++;
                        continue;
                    }
                }

                // 注册用户
                System.out.println("尝试注册用户: " + user.getUsername());
                if (userService.register(user)) {
                    System.out.println("用户注册成功: " + user.getUsername());
                    successCount++;
                } else {
                    System.out.println("用户注册失败: " + user.getUsername());
                    errorDetails.append("用户[").append(user.getUsername()).append("]: 注册失败; ");
                    errorCount++;
                }

            } catch (Exception e) {
                System.out.println("处理用户时发生异常: " + user.getUsername() + ", 异常: " + e.getMessage());
                errorDetails.append("用户[").append(user.getUsername()).append("]: ").append(e.getMessage()).append("; ");
                e.printStackTrace();
                errorCount++;
            }
        }

        result.put("success", successCount);
        result.put("skip", skipCount);
        result.put("error", errorCount);
        result.put("errorDetails", errorDetails.toString());
        return result;
    }
}
